//
//  FeedbackController.m
//  KMedicine
//
//  Created by 余伟康 on 16/7/6.
//  Copyright © 2016年 caomu. All rights reserved.
//
//  意见反馈

#import "FeedbackController.h"

@interface FeedbackController ()<UITableViewDataSource,UITableViewDelegate,UITextViewDelegate>

// UIview
@property (nonatomic,strong) UIView *headView;

// tableView
@property (nonatomic,strong) UITableView *tableView;

// dataArray
@property (nonatomic,strong) NSArray *dataArray;

// UItextView
@property (nonatomic,strong) UITextView *textView;

// UILabel - 提示文字
@property (nonatomic,strong) UILabel *prompt;

// UIButton - 提交按钮
@property (nonatomic,strong) UIButton *submitButton;

// 剩余可输入字数
@property (nonatomic,assign) NSInteger remainingNumber;

@property (nonatomic,assign) BOOL isTextViewEnable;


@end

@implementation FeedbackController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.navigationBar.hidden = NO;
    
    self.dataArray = @[@{@"icon":@"dianhua",@"intro":@"客服电话: 400-636-6113"},
                       @{@"icon":@"qq",@"intro":@"用户交流群: QQ 464768569"}];
    
    
    [self setupUI];

}

- (void)setupUI{
    
    // 设置headView
    [self setupHeadView];
    
    [self.view addSubview:self.headView];
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.top.mas_equalTo(self.headView.mas_bottom);
    } ];
    

    [self.tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
}

#pragma mark
#pragma mark - 设置headView
- (void)setupHeadView{
    if (!_headView) {
        // --------------------- textView ---------------------//
        self.textView = [[UITextView alloc]init];
        self.textView.font = [UIFont fontWithName:@"Arial" size:18];
        self.textView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        self.textView.textAlignment = NSTextAlignmentNatural;
        
        // 禁用自动偏移
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        
        // 代理监听
        self.textView.delegate = self;
        
        self.textView.backgroundColor = GRAY_COLOR;
        _headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 300)];
        _headView.backgroundColor = [UIColor whiteColor];
        
        [self.headView addSubview:self.textView];
        
        [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsMake(10, 10, 40, 10));
        }];
        
        // --------------------- button ---------------------//
        self.submitButton = [[UIButton alloc]init];
        [self.submitButton setImage:[UIImage imageNamed:@"dijiaofankui"] forState:UIControlStateNormal];
        [self.headView addSubview:self.submitButton];
        [self.submitButton addTarget:self
                              action:@selector(submit:)
                    forControlEvents:UIControlEventTouchUpInside];
        [self.submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(-4);
            make.right.mas_equalTo(-10);
        }];
        
        // --------------------- label ---------------------//
        
        self.prompt = [[UILabel alloc]init];
        self.prompt.text = @"您还可以输入的字数为:200  ";
        [self.headView addSubview:self.prompt];
        [self.prompt mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.submitButton.left).offset(-10);
            make.bottom.mas_equalTo(-8);
        }];
    }

}

#pragma mark
#pragma mark - 点击提交反馈
- (void)submit:(UIButton *)button{

    NSLog(@"点击了提交");
    [self.view endEditing:YES];
}


#pragma mark
#pragma mark - UITextViewDelegate

// 防止键盘挡住输入
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{

    if (range.location >= 200) {
        return NO;
    }else {
    
        return YES;
    }
    
    
}

- (void)textViewDidChange:(UITextView *)textView{

    if (textView.text.length == 0) {
        
        self.submitButton.enabled = NO;
        }else{
            self.submitButton.enabled = YES;
        }
    [self textChange:textView.text];
    
    
}

// 检测文字的改变
-(void)textChange:(NSString *)text{
    
    static const NSInteger Max_Num_TextView = 200;
    
    self.isTextViewEnable = true;
    //获取当前键盘类型
    UITextInputMode *mode = (UITextInputMode *)[UITextInputMode activeInputModes][0];
    
    //获取当前键盘语言
    NSString *lang = mode.primaryLanguage;
    
    //如果语言是汉语(拼音)
    if ([lang isEqualToString:@"zh-Hans"])
    {
        
        //取到高亮部分范围
        UITextRange *selectedRange = [self.textView markedTextRange];
        
        //取到高亮部分
        UITextPosition *position = [self.textView positionFromPosition:selectedRange.start offset:0];
        
        //如果取不到高亮部分,代表没有拼音
        if (!position){
            
            //当期超过最大限制时
            if (self.textView.text.length > Max_Num_TextView) {
                
                //对超出部分进行裁剪
                self.textView.text = [self.textView.text substringToIndex:Max_Num_TextView];
                
                //同时对可继续书写属性设为否,shouldChangeTextInRange方法会调用
                self.isTextViewEnable = NO;
                
                //同时将下方提示label设置为0
                self.prompt.attributedText = [self handleColorStr:[NSString stringWithFormat:@"您还可以输入0个字"]];
            }
            
            //如果没超出,那么就计算剩余字数
            self.prompt.attributedText = [self handleColorStr:[NSString stringWithFormat:@"您还可以输入%ld个字",200-self.textView.text.length]];
            
        }else{
            //表示还有高亮部分，暂不处理
        }
        
    }else{
        //如果语言不是汉语,直接计算
        if (self.textView.text.length > Max_Num_TextView) {
            
            self.textView.text = [self.textView.text substringToIndex:Max_Num_TextView];
            self.isTextViewEnable = NO;
            
            self.prompt.attributedText = [self handleColorStr:[NSString stringWithFormat:@"您还可以输入0个字"]];
            
        }
        
        self.prompt.attributedText = [self handleColorStr:[NSString stringWithFormat:@"您还可以输入%ld个字",200-self.textView.text.length]];
        
    }
    
}

//对字的位置颜色进行处理
-(NSMutableAttributedString*)handleColorStr:(NSString*)str{
    
    NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc]initWithString:str];
    
    if (attStr.length == 11) {
        
        [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(6, 3)];
    }else if(attStr.length == 10){
        
        [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(6, 2)];
    }else{
        [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(6, 1)];
    }
    
    return attStr;
}

#pragma mark
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    NSString *imgName = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.row][@"icon"]];
    
    cell.imageView.image = [UIImage imageNamed:imgName];
    
    cell.textLabel.text = self.dataArray[indexPath.row][@"intro"];
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

    if (section == 0) {
        return @"欢迎联系我们";
    }
    return nil;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{

}

#pragma mark
#pragma mark - Lazy
- (UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        
        // 设置代理
        _tableView.dataSource =self;
        _tableView.delegate = self;
        
        self.tableView.scrollEnabled =NO;
    }
    return _tableView;
}

@end
